package com.lxb.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxb.eduservice.entity.EduComment;
import com.lxb.eduservice.mapper.EduCommentMapper;
import com.lxb.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxb.eduservice.vo.front.EduCommentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 评论 服务实现类
 *
 * @author lixuebin
 * @since 2023-01-11
 */
@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {

    @Override
    public EduCommentVo callBack(String commentId) {
        System.out.println(commentId);
        EduCommentVo commentVo = new EduCommentVo();

        //1.获取评论
        // 查询一级评论信息
        EduComment eduComment = baseMapper.selectById(commentId);
        //复制一级数据到vo类中
        BeanUtils.copyProperties(eduComment, commentVo);

        //查询二级评论
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        //查询当前 评论id 与 父id 是否一致
        wrapper.eq("pid", eduComment.getId());
        //按照插入时间，降序
        wrapper.orderByDesc("gmt_create");
        //评论集合
        List<EduComment> eduCommentList = baseMapper.selectList(wrapper);
        //设置当前评论数据，的回复集合


        //2.查询回复数据中，是否有子回复
        //存放回复数据集合
        List<EduCommentVo> CommentAllList = new ArrayList<>();
        EduCommentVo VoComment = new EduCommentVo();
        //遍历评论集合，查询每条记录数是否有回复
        if (eduCommentList != null) {
            //递归判断
            for(EduComment list : eduCommentList){

                BeanUtils.copyProperties(list,VoComment);
                //查询评论id，是否有子评论
                QueryWrapper<EduComment> wrapperCount = new QueryWrapper<>();
                wrapperCount.eq("pid",list.getId());
                Integer countIsHasComment = baseMapper.selectCount(wrapperCount);

                //有回复数，调用callBack，增加到children字段
                if (countIsHasComment>0){
                     VoComment = callBack(list.getId());
                }
                //增加回复数据
                CommentAllList.add(VoComment);
            }
            //设置当前评论数据，的回复集合
            commentVo.setChildren(CommentAllList);
        }

        return commentVo;
    }
}
